<?php
namespace  crontab\server;

use Workerman\Worker;
class TaskWoker{
    private $worker;

    private  $workerName = 'TaskWorker';

    public function __construct(array $context = []) {
        $this->initServer($context);
    }

    private function initServer($context = []) {
        $this->socketAddr = 'text://127.0.0.1:12341';

        $this->worker = new Worker('text://127.0.0.1:12341');
        $this->worker->name = $this->workerName?:'TaskWorker';
        //设置回调处理
        $this->eventRegist();
    }

     //设置默认应用层发送缓冲区大小。默认1M。可以动态设置
    public function setBufferSize($size = 1024 * 1024){
        TcpConnection::$defaultMaxSendBufferSize = $size;
        return $this;
    }

    //设置进程名称
    public function setCount($number = 1){
       $this->worker->count = $number;
        return $this;
    }

    //设置进程名称
    public function setWorkerName($name = "TaskWorker"){
       $this->worker->workerName = $name;
        return $this;
    }


    //设置进程端口复用
    public function setReusePort(){
       $this->worker->reusePort = true;
        return $this;
    }

    //以daemon(守护进程)方式运行
    public function setDaemon($bool = false) {
        Worker::$daemonize = $bool;
        return $this;
    }

    //注册回调函数
    private function eventRegist() {
        $this->worker->onWorkerStart = ['\crontab\event\ExecEvent', 'onWorkerStart'];
        $this->worker->onMessage    = ['\crontab\event\ExecEvent', 'onMessage'];
        $this->worker->onClose      = ['\crontab\event\ExecEvent', 'onClose'];
        $this->worker->onError       = ['\crontab\event\ExecEvent', 'onError'];
    }

    public function run() {
        if(!defined('GLOBAL_START')){
            Worker::runAll();
        }
    }

}
